<!-- markdown 文档 -->

<template>
	<div class="content">
		<div class="header my-animation-slide-top">
			<!-- 背景图片 -->
			<el-image class="my-el-image poem-image" style="position: absolute" v-once
				:src="require('@/assets/images/LearningDocument.jpg')" fit="cover">
				<div slot="error" class="image-slot"></div>
			</el-image>

			<div class="title">
				<div class="ai-center flex">
					<span class="tag-item ai-center flex">
						<svg class="icon" aria-hidden="true" style="width: 18px; height: 18px; margin-right: 3px">
							<use xlink:href="#icon-biaoqian"></use>
						</svg>笔记、学习</span>
				</div>
				<span class="fs-26 p-tb-15 fw-800">这是一个标题</span>
				<div class="ai-center flex p-b-10">
					<span class="tag-item ai-center flex">
						<svg class="icon" aria-hidden="true" style="width: 18px; height: 18px; margin-right: 3px">
							<use xlink:href="#icon-naozhong"></use>
						</svg>发表于2023-01-10
					</span>
					<span class="tag-item ai-center flex">
						<svg class="icon" aria-hidden="true" style="width: 20px; height: 20px; margin-right: 3px">
							<use xlink:href="#icon-xingyue"></use>
						</svg>
						更新2023-01-10
					</span>
				</div>
				<div class="ai-center flex">
					<span class="tag-item ai-center flex">
						<svg class="icon" aria-hidden="true" style="width: 20px; height: 20px; margin-right: 3px">
							<use xlink:href="#icon-xiewenzhang"></use>
						</svg>字数总计5.7K
					</span>
					<span class="tag-item ai-center flex">
						<svg class="icon" aria-hidden="true" style="width: 20px; height: 20px; margin-right: 3px">
							<use xlink:href="#icon-huanjiaowenzhang"></use>
						</svg>阅读量：123
					</span>
					<span class="tag-item ai-center flex">
						<svg class="icon" aria-hidden="true" style="width: 20px; height: 20px; margin-right: 3px">
							<use xlink:href="#icon--pinglun"></use>
						</svg>评论数：8
					</span>
				</div>
			</div>
		</div>
		<!-- class的值必须包含 markdown-body -->
		<div class="markdown-body html-content my-animation-slide-right" style="width: calc(100%)">
			<!-- <md></md> -->
			<section :is="articleComponent"></section>
		</div>
		<div class="md-siber">
			<div class="toc card my-animation-slide-left">
				<div class="fs-20 ai-center flex jc-center">目录</div>
			</div>
		</div>
	</div>
</template>

<script>
// markdown样式
import "github-markdown-css";
// 代码高亮
import "highlight.js/styles/github.css";

// import md from './interview.md'

export default {
	name: "Index",
	// components: { md },
	data() {
		return {
			treeData: [],
			defaultProps: {
				label: "text",
				children: "children",
			},
			isClickToJump: false,
			articleComponent: "",
		};
	},
	created() {
		this.$nextTick(() => {
			this.tocList();
		});
	},

	mounted() {
		// console.log("this.#route :>> ", this.$route.query.article);
		// this.articleComponent = require(`@/articleMd/interview.md`).default;
		// console.log("articleComponent :>> ", this.articleComponent);

		let article = this.$route.query && this.$route.query.article;
		console.log("article :>> ", article);
		this.articleComponent = require(`@/articleMd/${article}.md`).default;
		console.log("articleComponent :>> ", this.articleComponent);
	},
	methods: {
		getid() {
			const r = URL.createObjectURL(new Blob());
			return "cs" + r.substr(r.lastIndexOf("/") + 1, r.length - 1);
		},
		tocList() {
			const toc = document.querySelector(".toc");
			// const elements = document.querySelectorAll("h1, h2 ");

			var elements = $(":header");
			if (!elements.length) return;
			const HList = ["H1", "H2", "H3", "H4", "H5", "H6"];
			// 生成目录
			let str = `<div class="dir">\n<ul id="toc">`;
			Array.from(elements, (v) => {
				let uuid = this.getid();
				v.setAttribute("id", uuid);
				const H = HList.indexOf(v.nodeName) + 1 || 1;
				str += `<li class="li li-${H} "><a class="overflowClip" href="javascript:void(0);" id="${v.id}" >${v.textContent}</a></li>\n`;
			});
			str += `</ul>\n`;
			// str += `<div class="sider"><span class="siderbar"><span></div>\n</div>`;
			// 添加目录到页面
			toc.insertAdjacentHTML("beforeend", str);
			// 给目录添加点击事件
			Array.from(elements, (v) => {
				const btn = document.querySelector(`#toc #${v.id}`);
				const ele = document.querySelector(`.html-content #${v.id}`);
				if (!btn || !ele) return;

				btn.addEventListener("click", () => {
					console.log("ele.offsetTop :>> ", ele, ele.offsetTop);
					//点击目录滚动的距离 = 当前点击元素距离顶部的高度（offsetTop） - 标题dom距离顶部（留出最上层navbar的高度） + header的宽度（包括margin+padding）
					window.scrollTo({
						top: ele.offsetTop - 80 + 360,
						behavior: "smooth",
					});
					this.isClickToJump = true;
				});
			});
			if (elements.length > 0 && elements[0]) {
				document.querySelectorAll("#toc .li a")[0].classList.add("md-active");
			}
			// 监听滚动
			this.watchDocumentScroll(elements);
		},

		// 移除所有的 md-active 排他
		removeClass() {
			const list = document.querySelectorAll("#toc .li a");
			Array.from(list, (v) => v.classList.remove("md-active"));
		},

		watchDocumentScroll(elements) {
			window.addEventListener("scroll", () => {
				this.handleScroll(elements);
			});
		},
		handleScroll(elements) {
			const markupLi = document.querySelectorAll("#toc .li a");
			let lastScrollTop = 0;
			let selectiIndex = null;
			const currentScrollTop = document.documentElement.scrollTop;
			// 这里是是对向上还是向下滚动做处理；大于零向下，反之向上
			if (currentScrollTop - lastScrollTop > 0 || this.isClickToJump) {
				this.isClickToJump = false;
				Array.from(elements, (item, index) => {
					let reat = item.getBoundingClientRect();
					// 这里的判断是找到需要高亮的导航目录元素，当标题dom距离顶部小于80那么此标题dom就是高亮标题（reat.bottom指的是元素底部距离顶部的距离）；向上滚动就请coder脑补一下子把
					if (reat.top < 80 && reat.bottom > 0) {
						//清除导航样式函数
						this.removeClass();
						selectiIndex = index;
					}
				});
			} else {
				Array.from(elements, (item, index) => {
					let reat = item.getBoundingClientRect();
					if (reat.top > 80 && reat.bottom < 150) {
						//清除导航样式函数
						this.removeClass();
						index === 0 ? (selectiIndex = index) : (selectiIndex = index - 1);
					}
				});
			}
			if (selectiIndex !== null) {
				markupLi[selectiIndex].classList.add("md-active");
				//大于4的原因是：我将导航高度设置了300，每个标题30，因此导航最高展示10个元素所以当下标大于4的即5个元素时开始触发导航目录的滚动轴
				if (selectiIndex >= 4) {
					document.querySelector(".toc").scrollTo({
						top: Math.floor(markupLi[selectiIndex - 4].offsetTop),
						behavior: "smooth",
					});
				} else {
					document.querySelector(".toc").scrollTo({
						top: 0,
						behavior: "smooth",
					});
				}
			}

			lastScrollTop = currentScrollTop;

			const toc = document.querySelector(".toc");
			if (currentScrollTop > 150) {
				toc && toc.classList.add("tocScroll");
			} else {
				toc && toc.classList.remove("tocScroll");
			}
		},
	},
	destroyed() {
		window.removeEventListener("scroll", () => {
			this.handleScroll();
		});
	},
};
</script>

<style lang="scss" scoped>
.content {
	height: 100%;

	.header {
		height: 300px;
		width: 100%;
		font-family: "楷体";
		color: #fff;

		.my-el-image {
			width: 100%;
			height: 100%;
		}

		.title {
			display: flex;
			justify-content: center;
			position: relative;
			height: calc(100%);
			flex-direction: column;
			align-items: flex-start;
			// animation: zoomIn 0.8s ease-in-out;
			padding: 0 50px;

			.tag-item {
				background: #ffffff61;
				padding: 5px 10px;
				border-radius: 5px;
				margin-right: 20px;
			}
		}

		.content {
			padding: 30px 0;
			font-size: 22px;
		}
	}

	.html-content {}
}

// 头部图片自适应============================================
$sm: 1000px+30px !default;
/* 在这里，我们定义 CSS @media 查询来设置不同宽度范围的网页样式 */
/* 当屏幕宽度大于等于769px时 */
@media only screen and (min-width: $sm) {

	/* 在这里，我们可以设置大屏幕下的网页样式 */
	.header {
		width: 100%;
	}

	.html-content {
		padding: 15px calc((100% - 1000px) / 2);
	}
}

/* 当屏幕宽度大于等于481px且小于等于769px时 */
@media (max-width: 768px) and (min-width: 481px) {
	/* 在这里，我们可以设置中等屏幕下的网页样式 */
}

/* 当屏幕宽度小于等于769px时 */
@media only screen and (max-width: $sm) {
	.header {
		width: 100%;
	}

	.html-content {
		padding: 15px;
	}
}
</style>
